<template>
  <div v-loading="loading" class="MedicalGRfid">
    <div class="form-seach">
      <el-form ref="form" :rules="rules3" :model="BindForm" label-width="90px" label-position="left">
        <el-form-item label="RFID编号:" prop="rfidCode">
          <el-col :span="24">
            <el-input v-model="BindForm.rfidCode" placeholder="请输入RFID编号" maxlength="20" class="cus-input" clearable />
          </el-col>
        </el-form-item>
        <el-form-item label="商品:" prop="goods">
          <el-col :span="24">
            <select-goods ref="selectGoods" v-model="BindForm.goods" />
          </el-col>
        </el-form-item>
        <el-form-item prop="allCity" label="地区:">
          <el-col :span="24" style="align-items: center;display: flex;">
            <el-checkbox v-model="BindForm.allCity" label="全部" border @change="changedAllCity" />
            <city-select ref="citySelect" v-model="BindForm.address" @change="changedAddress" />
          </el-col>
        </el-form-item>
        <el-form-item prop="store" label="门店:">
          <el-col :span="24">
            <store-select ref="storeSelect" v-model="BindForm.store" field="id" />
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">筛选</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="ele-content">
      <div class="ele-to-sl">
        <div>
          <el-radio-group v-model="BindForm.state" @change="search">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="0">上线</el-radio-button>
            <el-radio-button label="1">下线</el-radio-button>
            <el-radio-button label="2">维护中</el-radio-button>
            <el-radio-button label="3">使用中</el-radio-button>
            <el-radio-button label="4">已销售</el-radio-button>
          </el-radio-group>
        </div>
        <div>
          <el-button
            type="primary"
            @click="$router.push({ name: 'AddCommodity' })"
          >新增RFID商品</el-button>
        </div>
      </div>
    </div>
    <div class="ele-table">
      <el-table ref="table" :data="BindTable" border max-height="600" :empty-text="loading ? '数据加载中' : (isSearch ? '未找到相关的RFID商品' : '暂无RFID商品')" @selection-change="handleSelectionChange">
        <el-table-column :selectable="selectable" type="selection" fixed="left" width="40" :resizable="false" />
        <el-table-column
          label="RFID编号"
          prop="rfidCode"
          align="center"
          width="100"
          :resizable="false"
          fixed="left"
        />
        <el-table-column
          label="商品编号"
          prop="commdityId"
          align="center"
          width="100"
          :resizable="false"
          fixed="left"
        />
        <el-table-column
          label="商品名称"
          prop="commdityName"
          align="center"
          :resizable="false"
          min-width="150"
        />
        <el-table-column
          label="商品规格"
          prop="commditySkuName"
          align="center"
          width="150"
          :resizable="false"
        />
        <el-table-column
          label="医柜锁"
          prop="medicalCode"
          align="center"
          :resizable="false"
          min-width="120"
        />
        <el-table-column
          label="归属门店"
          prop="storeName"
          align="center"
          :resizable="false"
          min-width="200"
        />
        <el-table-column
          label="商品类型"
          prop="commdityType"
          align="center"
          :resizable="false"
          min-width="100"
        ><template slot-scope="scope">
          <el-tag v-if="scope.row.commdityType == 'lease'" type="success" size="small">租赁</el-tag>
          <el-tag v-else-if="scope.row.commdityType == 'sale'" type="primary" size="small">售卖</el-tag>
          <el-tag v-else type="info" size="small">未知</el-tag>
        </template>
        </el-table-column>
        <el-table-column
          label="状态"
          prop="state"
          align="center"
          width="100"
          :resizable="false"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row['state'] == 0" type="success" size="small">上线</el-tag>
            <el-tag v-else-if="scope.row['state'] == 1" type="info" size="small">下线</el-tag>
            <el-tag v-else-if="scope.row['state'] == 2" type="warning" size="small">维护中</el-tag>
            <el-tag v-else-if="scope.row['state'] == 3" type="primary" size="small">使用中</el-tag>
            <el-tag v-else-if="scope.row['state'] == 4" type="danger" size="small">已销售</el-tag>
            <el-tag v-else type="info" size="small">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="维护备注"
          prop="reason"
          align="center"
          :resizable="false"
          width="150"
        />
        <el-table-column
          label="上线时间"
          prop="onlineTime"
          align="center"
          width="180"
          :resizable="false"
        />
        <el-table-column
          label="操作"
          header-align="center"
          align="left"
          fixed="right"
          width="215"
          :resizable="false"
        >
          <template slot-scope="scope" class="ele-template">
            <template v-if="scope.row['state'] == 0">
              <el-button type="text" @click="lowRow([scope.row])">下线</el-button>
              <el-button type="text" @click="defendRow([scope.row])">维护</el-button>
              <el-button type="text" @click="replaceRow(scope.row)">更换RFID</el-button>
              <el-button type="text" @click="deleteRow([scope.row])">删除</el-button>
            </template>
            <template v-else-if="scope.row['state'] == 1">
              <el-button type="text" @click="upRow([scope.row])">上线</el-button>
              <el-button type="text" @click="defendRow([scope.row])">维护</el-button>
              <el-button type="text" @click="replaceRow(scope.row)">更换RFID</el-button>
              <el-button type="text" @click="deleteRow([scope.row])">删除</el-button>
            </template>
            <template v-else-if="scope.row['state'] == 2">
              <el-button type="text" @click="upRow([scope.row])">上线</el-button>
              <el-button type="text" @click="lowRow([scope.row])">下线</el-button>
              <el-button type="text" @click="replaceRow(scope.row)">更换RFID</el-button>
              <el-button type="text" @click="deleteRow([scope.row])">删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <div>
        <div v-if="selectedList && selectedList.length > 0" style="display: inline-flex;">
          <el-button size="mini" type="info" @click="lowRow(selectedList)">下线（{{ selectedList.length }}）</el-button>
          <el-button size="mini" type="success" @click="upRow(selectedList)">上线（{{ selectedList.length }}）</el-button>
          <el-button size="mini" type="warning" @click="defendRow(selectedList)">维护（{{ selectedList.length }}）</el-button>
          <el-button size="mini" type="danger" @click="deleteRow(selectedList)">删除（{{ selectedList.length }}）</el-button>
        </div>
      </div>
      <div>
        <el-pagination
          background
          :page-sizes="[10, 20, 30, 50, 100]"
          :page-size="limit"
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="pageSizeChange"
          @current-change="currentPageChange"
        />
      </div>
    </div>

    <el-dialog :visible.sync="dialogVisible1" width="600px">
      <div v-if="tempList" slot="title">
        <b v-if="tempList && tempList.length == 1" class="def-b">维护【{{ tempList[0]['rfidCode'] }} - {{ tempList[0]['commdityName'] }}】RFID商品</b>
        <b v-else class="def-b">批量维护选中的【{{ tempList.length }}】个RFID商品</b>
      </div>
      <el-form ref="form1" :model="form1" :rules="rules1">
        <el-form-item label="维护备注:" prop="reason">
          <el-input
            v-model="form1.reason"
            type="textarea"
            :autosize="{ minRows: 7 }"
            maxlength="200"
            show-word-limit
            placeholder="请输入维护备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取消</el-button>
        <el-button type="primary" @click="submitDefend">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible2" width="600px">
      <div v-if="tempRow" slot="title">
        <b class="def-b">更换RFID【{{ tempRow['rfidCode'] }} - {{ tempRow['commdityName'] }}】</b>
      </div>
      <el-form v-if="tempRow" ref="form2" :model="form2" :rules="rules2">
        <el-form-item label="当前RFID编号:">
          <el-input :disabled="true" :value="form2.oldRfidCode" class="cus-input" />
        </el-form-item>
        <el-form-item label="新的RFID编号:" prop="newRfidCode">
          <el-input v-model="form2.newRfidCode" placeholder="请输入新的RFID编号" maxlength="20" class="cus-input" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取消</el-button>
        <el-button type="primary" @click="submitReplace">提交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
/** RFID商品 */
import CitySelect from '../../../components/CitySelect/index'
import StoreSelect from '../../../components/StoreSelect/index'
import SelectGoods from '../../../components/SelectGoods/index'
import { rfidCommodityList, changeRFIDCommodityState, changeRFIDCommodityRFID, deleteRFIDCommodity } from '@/api/lockItem'
import { Loading } from 'element-ui'
export default {
  name: 'MedicalGRfid',
  components: { SelectGoods, StoreSelect, CitySelect },
  data() {
    var validateNumber = (rule, value, callback) => {
      var Regx = /^[a-zA-Z0-9]*$/
      if (!Regx.test(value)) {
        callback(new Error('请输入正确的RFID编号'))
      } else {
        callback()
      }
    }
    return {
      page: 1,
      limit: 10,
      total: 0,
      loading: false,
      isSearch: false,
      BindForm: {
        allCity: true,
        rfidCode: null,
        goods: null,
        state: 'all',
        store: null,
        address: {
          province: null,
          city: null,
          village: null
        }
      },
      BindTable: [],
      selectedList: [],
      tempList: null,
      tempRow: null,
      dialogVisible1: false,
      dialogVisible2: false,
      form1: {
        reason: null
      },
      form2: {
        oldRfidCode: null,
        newRfidCode: null
      },
      rules1: {
        reason: [
          { required: true, message: '请输入维护备注', trigger: 'change' }
        ]
      },
      rules2: {
        newRfidCode: [
          { required: true, message: '请输入新的RFID编号', trigger: 'change' },
          { validator: validateNumber, trigger: 'change' }
        ]
      },
      rules3: {
        rfidCode: [
          { validator: validateNumber, trigger: 'change' }
        ]
      },
      isDeactivated: false
    }
  },
  created() {
    if (!this.isDeactivated) {
      this.loadTableData()
    }
  },
  activated() {
    if (this.isDeactivated) {
      this.isDeactivated = false
      this.loadTableData()
    }
  },
  deactivated() {
    this.isDeactivated = true
  },
  methods: {
    resetForm() {
      const vm = this
      vm.$refs.citySelect.resetFields()
      vm.$refs.form.resetFields()
      vm.reloadTableData()
    },
    changedAllCity() {
      const vm = this
      if (vm.BindForm.allCity) {
        if (vm.BindForm.address.province || vm.BindForm.address.city || vm.BindForm.address.village) {
          vm.$refs.citySelect.resetFields()
        }
      } else {
        if (!vm.BindForm.address.province || !vm.BindForm.address.city || !vm.BindForm.address.village) {
          vm.BindForm.allCity = true
        }
      }
    },
    changedAddress() {
      const vm = this
      if (vm.BindForm.address.province || vm.BindForm.address.city || vm.BindForm.address.village) {
        vm.BindForm.allCity = false
      } else {
        vm.BindForm.allCity = true
      }

      const provinceId = vm.BindForm.address.province ? vm.BindForm.address.province.code : null
      const cityId = vm.BindForm.address.city ? vm.BindForm.address.city.code : null
      const villageId = vm.BindForm.address.village ? vm.BindForm.address.village.code : null

      vm.$refs.storeSelect.refresh(provinceId, cityId, villageId)
    },
    search() {
      const vm = this
      vm.$refs.form.validate((valid) => {
        if (valid) {
          vm.reloadTableData()
        }
      })
    },
    pageSizeChange(pageSize) {
      const vm = this

      vm.limit = pageSize

      vm.$refs.form.validate((valid) => {
        if (valid) {
          vm.reloadTableData()
        }
      })
    },
    currentPageChange(page) {
      const vm = this

      vm.page = page

      vm.$refs.form.validate((valid) => {
        if (valid) {
          vm.loadTableData()
        }
      })
    },
    reloadTableData() {
      const vm = this

      vm.page = 1
      vm.total = 0
      vm.BindTable = []
      vm.loadTableData()
    },
    loadTableData() {
      const vm = this

      vm.isSearch = false

      const data = {
        page: vm.page,
        limit: vm.limit,
        shopId: parseInt(localStorage.getItem('shopId'))
      }

      if (vm.BindForm.rfidCode && vm.BindForm.rfidCode.length > 0) {
        data['rfidCode'] = vm.BindForm.rfidCode
        vm.isSearch = true
      }

      if (vm.BindForm.store && vm.BindForm.store > 0) {
        data['storeId'] = parseInt(vm.BindForm.store)
        vm.isSearch = true
      }

      if (vm.BindForm.state !== 'all') {
        data['state'] = parseInt(vm.BindForm.state)
        vm.isSearch = true
      }

      if (vm.BindForm.address.province || vm.BindForm.address.city || vm.BindForm.address.village) {
        data['address'] = {}
        if (vm.BindForm.address.province) {
          data['address']['province'] = vm.BindForm.address.province.code
        }
        if (vm.BindForm.address.city) {
          data['address']['city'] = vm.BindForm.address.city.code
        }
        if (vm.BindForm.address.village) {
          data['address']['area'] = vm.BindForm.address.village.code
        }
        vm.isSearch = true
      }

      if (vm.BindForm.goods) {
        data['commdityId'] = parseInt(vm.BindForm.goods.goodsId)
        vm.isSearch = true
      }

      vm.loading = true

      rfidCommodityList(data).then(res => {
        vm.loading = false
        vm.total = res.data.data.total
        vm.BindTable = res.data.data.data ? res.data.data.data : []
      }).catch(res => {
        vm.loading = false
        if (res && res.data && res.data.errno !== 0) {
          this.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
        }
      })
    },
    handleSelectionChange(val) {
      this.selectedList = val
    },
    selectable(row, index) {
      if (row['state'] === 0 || row['state'] === 1 || row['state'] === 2) {
        return true
      }
      return false
    },
    deleteRow(list) {
      const vm = this

      let msg = '确定删除【' + list[0]['rfidCode'] + ' - ' + list[0]['commdityName'] + '】RFID商品吗？'
      if (list.length > 1) {
        msg = '确定批量删除选中的【' + list.length + '】个RFID商品吗？'
      }

      vm.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loadingInstance = Loading.service()
        deleteRFIDCommodity({
          idList: vm.$XEUtils.pluck(list, 'rfidCode')
        }).then(res => {
          loadingInstance.close()
          vm.$message.success('删除RFID商品成功')
          vm.reloadTableData()
        }).catch(res => {
          loadingInstance.close()
          if (res && res.data && res.data.errno !== 0) {
            vm.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
          }
        })
      }).catch(() => {})
    },
    lowRow(list) {
      const vm = this

      let msg = '确定下线【' + list[0]['rfidCode'] + ' - ' + list[0]['commdityName'] + '】RFID商品吗？'
      if (list.length > 1) {
        msg = '确定批量下线选中的【' + list.length + '】个RFID商品吗？'
      }

      vm.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loadingInstance = Loading.service()
        changeRFIDCommodityState({
          idList: vm.$XEUtils.pluck(list, 'rfidCode'),
          type: 1
        }).then(res => {
          loadingInstance.close()
          vm.$message.success('下线RFID商品成功')
          vm.reloadTableData()
        }).catch(res => {
          loadingInstance.close()
          if (res && res.data && res.data.errno !== 0) {
            vm.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
          }
        })
      }).catch(() => {})
    },
    upRow(list) {
      const vm = this

      let msg = '确定上线【' + list[0]['rfidCode'] + ' - ' + list[0]['commdityName'] + '】RFID商品吗？'
      if (list.length > 1) {
        msg = '确定批量上线选中的【' + list.length + '】个RFID商品吗？'
      }

      vm.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loadingInstance = Loading.service()
        changeRFIDCommodityState({
          idList: vm.$XEUtils.pluck(list, 'rfidCode'),
          type: 0
        }).then(res => {
          loadingInstance.close()
          vm.$message.success('上线RFID商品成功')
          vm.reloadTableData()
        }).catch(res => {
          loadingInstance.close()
          if (res && res.data && res.data.errno !== 0) {
            vm.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
          }
        })
      }).catch(() => {})
    },
    defendRow(list) {
      const vm = this
      vm.tempList = list
      vm.dialogVisible1 = true
      vm.$nextTick(() => {
        vm.$refs.form1.resetFields()
      })
    },
    replaceRow(row) {
      const vm = this
      vm.form2.oldRfidCode = row['rfidCode']
      vm.tempRow = row
      vm.dialogVisible2 = true
      vm.$nextTick(() => {
        vm.$refs.form2.resetFields()
      })
    },
    submitDefend() {
      const vm = this
      vm.$refs.form1.validate((valid) => {
        if (valid) {
          const loadingInstance = Loading.service()
          changeRFIDCommodityState({
            idList: vm.$XEUtils.pluck(vm.tempList, 'rfidCode'),
            reason: vm.form1.reason,
            type: 2
          }).then(res => {
            loadingInstance.close()
            vm.dialogVisible1 = false
            vm.$message.success('维护RFID商品成功')
            vm.reloadTableData()
          }).catch(res => {
            loadingInstance.close()
            if (res && res.data && res.data.errno !== 0) {
              vm.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
            }
          })
        }
      })
    },
    submitReplace() {
      const vm = this
      vm.$refs.form2.validate((valid) => {
        if (valid) {
          const loadingInstance = Loading.service()
          changeRFIDCommodityRFID(vm.form2).then(res => {
            loadingInstance.close()
            vm.dialogVisible2 = false
            loadingInstance.close()
            vm.$message.success('更换RFID成功')
            vm.reloadTableData()
          }).catch(res => {
            loadingInstance.close()
            if (res && res.data && res.data.errno !== 0) {
              vm.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .MedicalGRfid {
    .form-seach {
      padding: 20px 30px;
      padding-bottom: 0px;
      margin-bottom: 30px;
      border: 1px solid #eeeeee;
      .cus-input {
        max-width: 400px;
      }
    }
    .ele-content {
      width: 100%;
      .ele-to-sl {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
      }
    }
    .ele-table,
    .pagination {
      margin-bottom: 30px;
    }
    .pagination {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }

  .def-b {
    border-left: 4px solid rgb(55, 131, 255);
    padding-left: 10px;
  }

</style>

